package pack0923;

import java.util.Arrays;

// 找出数组中的最大值
public class DemoE {

    // 通过打擂台方式获取到最大值
    public static void a() {
        int len = (int) (Math.random() * 20 + 10);
        int[] array = new int[len];
        for (int i = 0; i < len; i++) {
            array[i] = (int) (Math.random() * 100 + 1);
        }
        // 输出数组
        System.out.println(Arrays.toString(array));
        int max = array[0];
        for (int i = 1; i < array.length; i++) {
            if (max < array[i]) {
                max = array[i];
            }
        }
        System.out.println("最大值是：" + max);
    }

    // 通过打擂台方式获取到最大值以及下标
    public static void b() {
        int len = (int) (Math.random() * 20 + 10);
        int[] array = new int[len];
        for (int i = 0; i < len; i++) {
            array[i] = (int) (Math.random() * 100 + 1);
        }
        // 输出数组
        System.out.println(Arrays.toString(array));
        int max = array[0];
        int maxIndex = 0;
        for (int i = 1; i < array.length; i++) {
            if (max < array[i]) {
                max = array[i];
                maxIndex = i;
            }
        }
        System.out.println("最大值是：" + max + ",下标是：" + maxIndex);
    }

    // 通过打擂台方式获取到最小值
    public static void c() {
        int len = (int) (Math.random() * 20 + 10);
        int[] array = new int[len];
        for (int i = 0; i < len; i++) {
            array[i] = (int) (Math.random() * 100 + 1);
        }
        // 输出数组
        System.out.println(Arrays.toString(array));
        int min = array[0];
        for (int i = 1; i < array.length; i++) {
            if (min > array[i]) {
                min = array[i];
            }
        }
        System.out.println("最小值是：" + min);
    }

    // 求出数组中第二大的元素以及下标
    public static void d() {
        int len = (int) (Math.random() * 20 + 10);
        int[] array = new int[len];
        for (int i = 0; i < len; i++) {
            array[i] = (int) (Math.random() * 100 + 1);
        }
        // 输出数组
        System.out.println(Arrays.toString(array));
        int max = array[0];
        int maxIndex = 0;
        for (int i = 1; i < array.length; i++) {
            if (max < array[i]) {
                max = array[i];
                maxIndex = i;
            }
        }
        System.out.println("最大值是：" + max + ",下标是：" + maxIndex);
        int secondMax = array[0] == max ? array[1] : array[0];
        int secondMaxIndex = maxIndex == 0 ? 1 : 0;
        for (int i = secondMaxIndex + 1; i < len; i++) {
            // 最大值不参与比较
            if (i == maxIndex || max == array[i]) {
                continue;
            }
            if (secondMax < array[i]) {
                secondMax = array[i];
                secondMaxIndex = i;
            }
        }
        System.out.println("第二大值是：" + secondMax + ",第二大值下标是：" + secondMaxIndex);
    }

    // 求出数组中第二小的元素以及下标
    public static void main(String[] args) {
        d();
    }
}